import { ajax } from 'jquery'
import {each} from 'lodash'
import router from '../router'
const urlMap = {
	development: 'https://serviceprod.kpcb.org.cn',
	dev: 'https://serviceprod.kpcb.org.cn',
	production: 'https://serviceprod.kpcb.org.cn'
}
const baseUrl = urlMap[process.env.NODE_ENV]
export default function (options) {
  const {url, data, method, params} = options
  let requestUrl = url
  if (params) {
    requestUrl += '?'
    const paramsArr = []
    each(params, (value, key) => [
      paramsArr.push([key, value])
    ])
    requestUrl += paramsArr.map(e => e.join('=')).join('&')
  }
  return new Promise((resolve, reject) => {
    ajax({
      url: `${baseUrl}${requestUrl}`,
      headers: {
        Authorization: localStorage.getItem('token')
      },
      method,
      cache: false,
      async: false,
      crossDomain: true,
      contentType: 'application/json',
      dataType: 'json',
      data: data ? JSON.stringify(data) : undefined,
      success: res => {
        if (res.code !== 0) {
	        layer.msg(res.message, {icon: 5})
          return reject(res)
        }
        resolve(res.data)
      },
      error: (err) => {
        if (err.status === 401) {
          alert('凭证过期，请重新登录')
          return router.push('/login')
        }
	      layer.msg(err.message, {icon: 5})
        reject(err)
      }
    })
  })
}
